//
//  EasyWallet.swift
//  tappay_charge
//
//  Created by Warren L on 2024/7/22.
//

import TPDirect

typealias EasyWalletCommonCallback = (TappaySdkCommonResult) -> Void

typealias EasyWalletPaymentCallback = (TappayPaymentResult) -> Void

class EasyWallet: NSObject {
    var easyWallet: TPDEasyWallet!
    
    /// 支付回調
    var onEasyWalletResult: EasyWalletPaymentCallback?
    
    /// 獲取Easy Wallet Prime
    func getEasyWalletPrime(
        returnUrl: String,
        callback: EasyWalletPaymentCallback?
    ) {
        
        easyWallet = TPDEasyWallet.setup(withReturUrl: returnUrl)
        easyWallet
            .onSuccessCallback { prime in
                let successRetult = TappayPaymentResult(success: true, status: nil, message: "Get Easy Wallet prime was successful", prime: prime)
                callback?(successRetult)
            }
            .onFailureCallback { status, message in
                let errorResult = TappayPaymentResult(success: false, status: status, message: message, prime: nil)
                callback?(errorResult)
            }
            .getPrime()
    }
    
    /// 跳轉至Easy Wallet進行支付
    func redirectEasyWallet(
        paymentUrl: String,
        callback: EasyWalletPaymentCallback?
    ) {
        guard let easyWallet = easyWallet else {
            let errorResult = TappayPaymentResult(success: false, status: nil, message: "Please getEasyWalletPrime first", prime: nil)
            callback?(errorResult)
            return
        }
        
        self.onEasyWalletResult = callback
        
        easyWallet.redirect(paymentUrl) { result in
            print("stauts : \(result.status) , recTradeId : \(result.recTradeId ?? "") , bankTransactionId : \(result.bankTransactionId ?? "") , order_number : \(result.orderNumber ?? "")")
            
            if (result.status == 0) {   /// 0：成功
                let successResult = TappayPaymentResult(success: true, status: nil, message: "Redirect Easy Wallet was successful", prime: nil)
                callback?(successResult)
            } else {
                let errorResult = TappayPaymentResult(success: false, status: result.status, message: "Redirect Easy Wallet was failure", prime: nil)
                callback?(errorResult)
            }
        }
    }
}
